﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using BaseHelper;
using System.IO;
using System.Threading;
using System.Drawing;
using BaseHelper.Base;
using RTSDK;

namespace DeviceSDK.Park.Haikang
{
    public class HaiKang_TCR400
    {

        private static string _carcolor=" 白银灰黑红蓝蓝黄绿棕粉紫灰青";

        private static int[] _caridtypeid = new int[] { 1, 0, 7, 6, 4, 10, 12, 3, 19 };
        private static string[] _caridtypeidname = new string[] {"未知", "蓝牌小汽车", "黑牌小汽车", "单排黄牌", "双排黄牌", "警车", "武警", "个性车牌", "单排军车", "双排军车", "使馆车", "香港通行车", "农用车", "教练车", "澳门通行车", "双层武警车", "武警总队车", "双层武警总队车", "民航车牌", "新能源"};
        
       // private static string[] _caridtypeidname = new string[] { "蓝牌小汽车", "民用车牌", "武警车车牌", "警车车牌", "双排黄牌", "使馆车牌", "农用车车牌", "摩托车车牌", "新能源车牌" };


        private static HaiKangSDKV2.MSGCallBack_V31 m_falarmDataV31 = null;
        private static HaiKangSDKV2.MSGCallBack m_falarmData = null;
        //private static HaiKangSDKV2.EXCEPYIONCALLBACK m_fExceptionCB = null;

        private static uint iLastErr = 0;        
        private static bool IsInit = false;
        private static int iListenHandle;
        
        public static bool IsConnected(string IP)
        {
            return false;
            //return slUserHandlerList.ContainsValue(IP);  
        }

        //获取错误代码
        public static string Get_Error(int ret)
        {
            

            switch (ret)
            {
                case 0:
                    return "操作成功！";
                case 1:
                    return "操作失败！err" + iLastErr.ToString();
                case 2:
                    return "初始化接口失败！err" + iLastErr.ToString();
                case 3:
                    return "登录设备失败，请检测IP、用户名、密码和端口号！err" + iLastErr.ToString();
                case 4:
                    return "监听数据失败！err" + iLastErr.ToString();

                case 5:
                    return "初始化，设定回调接口出错！err" + iLastErr.ToString();

                case -1:
                    return "本设备不支持此命令！";
                default:
                    return "未知错误！";
            }
        }

        //设置初始化
        public static int Init()
        {
            try
            {
                bool m_bInitSDK = HaiKangSDKV2.NET_DVR_Init();
                if (m_bInitSDK == false)
                {
                    return 2;
                }
                else
                {

                    byte[] strIP = new byte[16 * 16];

                    //保存SDK日志 To save the SDK log
                    HaiKangSDKV2.NET_DVR_SetLogToFile(3, AppDomain.CurrentDomain.BaseDirectory + "\\Log\\", true);//可用可不用


                    //设置透传报警信息类型
                    HaiKangSDKV2.NET_DVR_LOCAL_GENERAL_CFG struLocalCfg = new HaiKangSDKV2.NET_DVR_LOCAL_GENERAL_CFG();
                    struLocalCfg.byAlarmJsonPictureSeparate = 1;//控制JSON透传报警数据和图片是否分离，0-不分离(COMM_VCA_ALARM返回)，1-分离（分离后走COMM_ISAPI_ALARM回调返回）


                    Int32 nSize = Marshal.SizeOf(struLocalCfg);
                    IntPtr ptrLocalCfg = Marshal.AllocHGlobal(nSize);
                    Marshal.StructureToPtr(struLocalCfg, ptrLocalCfg, false);
                
                    if (!HaiKangSDKV2.NET_DVR_SetSDKLocalCfg(17, ptrLocalCfg))  
                    {
                        iLastErr = HaiKangSDKV2.NET_DVR_GetLastError();
                        return 2;
                    }
                    Marshal.FreeHGlobal(ptrLocalCfg);


                    //if (m_fExceptionCB == null)
                    //    m_fExceptionCB = new HaiKangSDKV2.EXCEPYIONCALLBACK(cbExceptionCB);
                    //HaiKangSDKV2.NET_DVR_SetExceptionCallBack_V30(0, IntPtr.Zero, m_fExceptionCB, IntPtr.Zero);


                    //设置报警回调函数
                    if(m_falarmDataV31==null)
                        m_falarmDataV31 = new HaiKangSDKV2.MSGCallBack_V31(Get_MsgCallbackV31);

                    HaiKangSDKV2.NET_DVR_SetDVRMessageCallBack_V31(m_falarmDataV31, IntPtr.Zero);

                    IsInit = true;
                    return 0;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Err("RT.HelperDevice.Radar.Haikang.Haikang_TCR400.cs", "Init()", ex);
            }
            return 2;
        }


        //public static void cbExceptionCB(uint dwType, int lUserID, int lHandle, IntPtr pUser)
        //{
        //    //异常消息信息类型
        //    string stringAlarm = "异常消息回调，信息类型：0x" + Convert.ToString(dwType, 16) + ", lUserID:" + lUserID + ", lHandle:" + lHandle;
        //    Console.WriteLine(stringAlarm);
       
        //}

        //设置关闭监听
        public static int Set_Close()
        {
            try
            {

                if (!HaiKangSDKV2.NET_DVR_StopListen_V30(iListenHandle))
                    iLastErr = HaiKangSDKV2.NET_DVR_GetLastError();

                bool ret = HaiKangSDKV2.NET_DVR_Cleanup();

                IsInit = false;
            }
            catch (Exception ex)
            {
                LogHelper.Err("RT.HelperDevice.Radar.Haikang.Haikang_TCR400.cs", "Set_Close()", ex);
            }
            GC.Collect();
            return 0;
        }


        public static int Set_Listen(string IP, string Port)
        {
            try
            {

                if (IsInit == false)
                {
                    int ret = Init();
                    if (ret != 0)
                        return ret;
                    IsInit = true;
                }

                if(m_falarmData==null)
                {
                    m_falarmData = new HaiKangSDKV2.MSGCallBack(Get_MsgCallback);
                }

                iListenHandle = HaiKangSDKV2.NET_DVR_StartListen_V30(IP, (ushort)Convert.ToInt32(Port), m_falarmData, IntPtr.Zero);
                if (iListenHandle < 0)
                {
                    iLastErr = HaiKangSDKV2.NET_DVR_GetLastError();
                    return 4;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Err("DeviceSDK.Park.Haiang.HaiKang_TCR400.cs", "Set_Listen()", ex);
            }

            return 0;

        }

        public static int Set_Connect(string IP, string Port, string User, string Pass)
        {

            try
            {
                if (IsInit == false)
                {
                    int ret = Init();
                    if (ret != 0)
                        return ret;
                    IsInit = true;
                }

                HaiKangSDKV2.NET_DVR_DEVICEINFO_V30 DeviceInfo = new HaiKangSDKV2.NET_DVR_DEVICEINFO_V30();

                int UserID = HaiKangSDKV2.NET_DVR_Login_V30(IP, Convert.ToInt32(Port), User, Pass, ref DeviceInfo);

                if (UserID < 0)
                {
                    iLastErr = HaiKangSDKV2.NET_DVR_GetLastError();
                    return 3;// (int)iLastErr;  登录设备失败，请检测IP、用户名、密码和端口号！
                }
                else
                {
                    HaiKangSDKV2.NET_DVR_SETUPALARM_PARAM struAlarmParam = new HaiKangSDKV2.NET_DVR_SETUPALARM_PARAM();

                    struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
                    struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
                    struAlarmParam.byAlarmInfoType = 1;//智能交通设备有效，新报警信息类型
                    struAlarmParam.byFaceAlarmDetection = 1;//1-人脸侦测

                    int ret = HaiKangSDKV2.NET_DVR_SetupAlarmChan_V41(UserID, ref struAlarmParam);

                    if (ret < 0)
                    {
                        iLastErr = HaiKangSDKV2.NET_DVR_GetLastError();
                        return 4;
                    }
                    else
                    {
                       
                        return 0;
                    }
                }
            }
            catch(Exception ex)
            {
                LogHelper.Err("DeviceSDK.Park.Haikang.HaiKang_TCR400.cs", "Set_Connect()", ex);
                return 3;
            }
        }
        private static void Get_MsgCallback(int lCommand, ref HaiKangSDKV2.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            Checking(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
        }
        private static bool Get_MsgCallbackV31(int lCommand, ref HaiKangSDKV2.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            Checking(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
            return true;
        }
        private static void Checking(int lCommand, ref HaiKangSDKV2.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {

            string IP=Encoding.Default.GetString(pAlarmer.sDeviceIP).Trim('\0');
            string DeviceID = Encoding.Default.GetString(pAlarmer.sDeviceName).Trim('\0');

            try
            {
            if (lCommand == HaiKangSDKV2.COMM_ALARM_AID_V41 || lCommand == HaiKangSDKV2.COMM_ALARM_AID)
            {

                HaiKangSDKV2.NET_DVR_AID_ALARM_V41 result = new HaiKangSDKV2.NET_DVR_AID_ALARM_V41();
                uint dwSize = (uint)Marshal.SizeOf(result);
                result = (HaiKangSDKV2.NET_DVR_AID_ALARM_V41)Marshal.PtrToStructure(pAlarmInfo, typeof(HaiKangSDKV2.NET_DVR_AID_ALARM_V41));
                Console.WriteLine(result);

            }
            else if (lCommand == HaiKangSDKV2.COMM_ALARM_TFS )
            {
                #region 车辆处理
                
                    HaiKangSDKV2.NET_DVR_TFS_ALARM result = new HaiKangSDKV2.NET_DVR_TFS_ALARM();
                    uint dwSize = (uint)Marshal.SizeOf(result);
                    result = (HaiKangSDKV2.NET_DVR_TFS_ALARM)Marshal.PtrToStructure(pAlarmInfo, typeof(HaiKangSDKV2.NET_DVR_TFS_ALARM));


                    CarInfo car = new CarInfo();
    
                    car.PlaceID = Encoding.Default.GetString(result.struAIDInfo.byParkingID).TrimEnd('\0');
                    car.DeviceIP = IP;
                    car.Time = DateTime.Parse(result.struTime.wYear + "-" + result.struTime.byMonth + "-" + result.struTime.byDay + " " + result.struTime.byHour + ":" + result.struTime.byMinute + ":" + result.struTime.bySecond);// DateTime.Now;

                    if (result.struAIDInfo.byVehicleEnterState == 1)
                        car.ParkState = ParkState.Enter;
                    else if (result.struAIDInfo.byVehicleEnterState == 2)
                        car.ParkState = ParkState.Leave;
                    else
                        car.ParkState = ParkState.None;

                    //0   1停车  2离开
                    //Console.WriteLine(result.struVehicleInfo.byIsParking);


                    string CarID = Encoding.Default.GetString(result.struPlateInfo.sLicense).TrimEnd('\0');

                    if (CarID.Length >= 2)
                    {
                        //返回格式：蓝冀A123456
                        car.CarIDColor = CarID.Substring(0, 1); ;
                        car.CarAreaID = CarID.Substring(1, 1);
                        car.CarID = CarID.Substring(1, CarID.Length - 1);
                        car.CarIDShort = CarID.Substring(2, CarID.Length - 2);
                    }
                    else
                    {
                        car.CarIDColor = "";
                        car.CarAreaID = "";
                        car.CarID = "";
                        car.CarIDShort = "";
                    }
                    car.CarIDTypeID = _caridtypeid[(int)result.struPlateInfo.byPlateType].ToString();
                    car.CarIDTypeName = _caridtypeidname[_caridtypeid[(int)result.struPlateInfo.byPlateType]];

           
                    int colorID;
                    if (result.struVehicleInfo.byColor == 0 || result.struVehicleInfo.byColor == 255)
                    {
                        car.CarColor = result.struVehicleInfo.byColorDepth == 0 ? "深" : "浅";
                    }
                    else
                    {
                        colorID = result.struVehicleInfo.byColor;
                        car.CarColor = _carcolor[colorID].ToString();
                    }

                    //可信度
                    //result.struVehicleInfo.byBelieve;

                    if (result.dwPicNum > 0)
                    {
                        try
                        {
                          

                            //2张图片，第一张是摄像头合成后的，第二张是车牌特写
                            if(result.dwPicNum==3)
                            {
                                car.CarBodyPhoto = new byte[result.struPicInfo[0].dwDataLen];
                                Marshal.Copy(result.struPicInfo[0].pBuffer, car.CarBodyPhoto, 0, car.CarBodyPhoto.Length);
                                
                                //2020.3.27 暂时不压缩
                                //tmp = new byte[result.struPicInfo[0].dwDataLen];
                                //Marshal.Copy(result.struPicInfo[0].pBuffer, tmp, 0, tmp.Length);
                                //Image img = ImageHelper.ToImage(tmp);
                                //img = ImageHelper.GetThumb(img, ParkAutoHelper.ScaleWidth, ParkAutoHelper.ScaleHeight);
                                //car.CarBodyPhoto = ImageHelper.ToBytes(img);

                            }
                            else
                            {
                                byte[] tmp;
                       
                                int halfWidth=ParkAutoHelper.ScaleWidth/2;
                                int halfHeight=ParkAutoHelper.ScaleHeight/2;
                                Bitmap bigImage = new Bitmap(ParkAutoHelper.ScaleWidth, ParkAutoHelper.ScaleHeight);
                                Graphics g = Graphics.FromImage(bigImage);
                                g.FillRectangle(new SolidBrush(Color.Black), 0, 0, bigImage.Width, bigImage.Height);

                                //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                                //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;

                                for (int i = 0; i < result.dwPicNum - 1; i++)
                                {
                                    try
                                    {
                                        tmp = new byte[result.struPicInfo[i].dwDataLen];
                                        Marshal.Copy(result.struPicInfo[i].pBuffer, tmp, 0, tmp.Length);

                                        using (Image img = ImageHelper.ToImage(tmp))
                                        {
                 
                                            if (i == 0)
                                                g.DrawImage(img, new Rectangle(0, 0, halfHeight, halfWidth), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                                            else if (i == 1)
                                                g.DrawImage(img, new Rectangle(halfHeight, 0, halfHeight, halfWidth), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                                            else if (i == 2)
                                                g.DrawImage(img, new Rectangle(0, halfWidth, halfHeight, halfWidth), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                                            else if (i == 3)
                                                g.DrawImage(img, new Rectangle(halfHeight, halfWidth, halfHeight, halfWidth), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Err("DeviceSDK.Park.Haikang.HaiKang_TCR400.cs", "Get_MsgCallback(ex)", ex);
                                    }
                                }

                                g.Dispose();

                                car.CarBodyPhoto = ImageHelper.ToBytes(bigImage, System.Drawing.Imaging.ImageFormat.Jpeg);
                                bigImage.Dispose();

                            }



                            car.CarIDPhoto = new byte[result.struPicInfo[result.dwPicNum-1].dwDataLen];
                            Marshal.Copy(result.struPicInfo[result.dwPicNum - 1].pBuffer, car.CarIDPhoto, 0, car.CarIDPhoto.Length);

                        }
                        catch (Exception ex2)
                        {
                            LogHelper.Err("DeviceSDK.Park.Haikang.HaiKang_TCR400.cs", "Get_MsgCallback(ex2)", ex2);
                        }
                    }


                    ParkHandler.OnCarArriveRoad(IP,car);


                }
               
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.Err("DeviceSDK.ParkHaikang.HaiKang_TCR400.cs", "Get_MsgCallback()", ex);
            }
        }
        
    }
}
